package cnpm02.j2ee.group3.logic.validator;

import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.hibernate.validator.Validator;

public class EmailValidator implements Validator<CustomEmail>, Serializable{
	    private static final long serialVersionUID = 1L;
	    
	    public static final String PATTERN = "\\b[a-z0-9._%+-]+@[a-z0-9._-]+\\.[a-z]{2,4}\\b";

	    private Pattern pattern;
	    
	    /**
	     * {@inheritDoc}
	     */
	    public void initialize(CustomEmail parameters) {
	        pattern = Pattern.compile(PATTERN);
	    }

	    /**
	     * {@inheritDoc}
	     */
	    public boolean isValid(Object value) {
	        if (value == null) {
	            return true;
	        }
	        if (!(value instanceof String)) {
	            return false;
	        }
	        
	        String string = (String) value;
	        if (string.length() == 0) {
	            return true;
	        }
	        
	        string = string.toLowerCase();
	        Matcher m = pattern.matcher(string);
	        return m.matches();
	    }
}
